<template>
  <el-dialog v-model="openBoole" :close-on-click-modal="false" custom-class="mydialog" width="50%" :title="title"
    @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="110px" size="small">
      <el-row gutter="40">
        <el-col :span="12">
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="openForm.contractName" clearable placeholder="请输入合同名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="contractType">
            <el-select v-model="openForm.contractType" style="width: 100%" placeholder="请选择合同类型">
              <el-option v-for="item in contractTypeData" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同对象" prop="contractObjectType">
            <el-select v-model="openForm.contractObjectType" :disabled="disabled" style="width: 100%"
              placeholder="请选择合同对象">
              <el-option v-for="item in contractObjectTypeData" :key="item.id" :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="相对方名称" prop="objectName">
            <el-autocomplete v-model="openForm.objectName" :disabled="disabled" style="width: 100%"
              placeholder="请输入相对方名称" :fetch-suggestions="querySearchAsync" @select="handleSelect">
              <template #default="{ item }">
                <div class="productName">
                  <span v-if="openForm.contractObjectType ==='agent'">{{ item.agentName }}</span>
                  <span v-if="openForm.contractObjectType ==='agent_person'">{{ item.userName }}</span>
                  <span v-if="openForm.contractObjectType ==='distribute'">{{ item.distributeName }}</span>
                  <span v-if="openForm.contractObjectType ==='terminal'">{{ item.terminalName }}</span>
                  <span v-if="openForm.contractObjectType ==='seller'">{{ item.sellerName }}</span>
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同日期" prop="date">
            <date-range-picker v-model:date="openForm.date" style="width: 100%" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" @change="handlDate" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="contractHeadId">
            <el-select v-model="openForm.contractHeadId" style="width: 100%" placeholder="请选择负责人"
              @change="handlChangeHead">
              <el-option v-for="item in headList" :key="item.id" :label="item.realName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="value">
            <el-cascader placement="bottom" v-model="openForm.value" clearable style="width:100%"
              :popper-append-to-body="false" placeholder="请选择归属部门" :options="departmentList"
              :props="{ checkStrictly: true, value:'id',label:'deptName' }" @change="handlCascader" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input v-model="openForm.contractAmount" clearable placeholder="请输入合同金额" @change="handlAmount">
              <template #append>
                <span>元</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合同附件" prop="contractFile">
            <upload-file-view ref="uploadFileView" :file-arr.sync="openForm.contractFile" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消
        </el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">提交审核
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  ref,
  toRefs,
} from "vue";
import { crmStore } from "@CRM/store";
import { useRoute } from "vue-router";
import { validateVENumber } from "@/utils/validate";

export default {
  name: "AddContract",
  props: {
    disabled: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, context) {
    const validateNum = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback();
      } else {
        if (validateVENumber(value)) {
          callback(new Error("格式不正确(最多保留两位小数)"));
        } else {
          callback();
        }
      }
    };
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    const api = inject("api");
    var data = reactive({
      openForm: {
        contractName: "",
        contractType: "",
        contractBeginTime: "",
        contractEndTime: "",
        contractAmount: null,
        contractFile: [],
        contractObjectType: "",
        objectId: null,
        objectName: "",
        contractHeadId: null,
        contractHeadName: "",
        contractDepartmentId: null,
        contractDepartmentName: "",
        date: null,
        value: [],
      },
      contractTypeData:
        crmStore.getters["dictionary/getDictionary"]["contract_type"] || [],
      contractObjectTypeData:
        crmStore.getters["dictionary/getDictionary"]["contract_object"] || [],
      title: "新建合同",
      openBoole: false,
      openRef: null,
      rules: {
        contractName: [
          { required: true, message: "请输入合同名称", trigger: "blur" },
        ],
        contractType: [
          { required: true, message: "请选择合同类型", trigger: "change" },
        ],
        contractObjectType: [
          { required: true, message: "请选择合同对象", trigger: "change" },
        ],
        date: [
          { required: true, message: "请选择合同日期", trigger: "change" },
        ],
        objectName: [
          { required: true, message: "请选择相对方名字", trigger: "change" },
        ],
        contractHeadId: [
          { required: true, message: "请选择合同负责人", trigger: "change" },
        ],
        contractAmount: [{ validator: validateNum, trigger: "blur" }],
      },
      uploadFileView: null,
      headList: [],
      departmentList: [],
      booleTrue: true,
    });

    const querySearchAsync = async (queryString, cb) => {
      const a = {
        module_type: data.openForm.contractObjectType,
        key_word: queryString,
      };
      let results = [];
      const res = await api.terminal.CONTRACT_NAME(a);
      if (res.code === 0) {
        results = res.data.list || [];
      }
      cb(results);
    };

    const handleSelect = (val) => {
      switch (data.openForm.contractObjectType) {
        case "agent":
          data.openForm.objectName = val.agentName;
          data.openForm.objectId = Number(val.id);
          break;
        case "agent_person":
          data.openForm.objectName = val.userName;
          data.openForm.objectId = Number(val.id);
          break;
        case "distribute":
          data.openForm.objectName = val.distributeName;
          data.openForm.objectId = Number(val.id);
          break;
        case "terminal":
          data.openForm.objectName = val.terminalName;
          data.openForm.objectId = Number(val.id);
          break;
        case "seller":
          data.openForm.objectName = val.sellerName;
          data.openForm.objectId = Number(val.id);
          break;
      }
    };

    const close = () => {
      data.openBoole = false;
      remove();
    };

    const remove = () => {
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val, value, boole) => {
      data.openForm = {
        contractName: "",
        contractType: "",
        contractBeginTime: "",
        contractEndTime: "",
        contractAmount: null,
        contractFile: [],
        contractObjectType: "",
        objectId: null,
        objectName: "",
        contractHeadId: null,
        contractHeadName: "",
        contractDepartmentId: null,
        contractDepartmentName: "",
        date: null,
      };
      if (boole) {
        data.openForm.contractHeadId = crmStore.getters["user/userInfo"].ID;
        data.openForm.contractHeadName =
          crmStore.getters["user/userInfo"].realName;
      }
      data.openBoole = true;
      data.openForm.objectId = Number(val.id);
      data.openForm.objectName = val.name;
      data.openForm.contractType = val.contractType;
      data.openForm.contractObjectType = val.contractObjectType;
      // if (val.contractObjectType === 'agent_person') {
      //   data.booleTrue = false
      // }

      if (value) {
        data.title = "编辑合同";
        for (const key in data.openForm) {
          data.openForm[key] = value[key];
        }
        data.openForm.id = value.id;
        data.openForm.date = [
          data.openForm.contractBeginTime,
          data.openForm.contractEndTime,
        ];
        const a = handlRecursive(
          data.departmentList,
          data.openForm.contractDepartmentId
        );
        const b = [];
        a.forEach((item) => {
          b.push(item.id);
        });
        data.openForm.value = b;
        data.openForm.contractDepartmentName = a[a.length - 1].name;
      } else {
        data.title = "新建合同";
      }
    };

    const handlDate = (val) => {
      if (val) {
        data.openForm.contractBeginTime = val[0];
        data.openForm.contractEndTime = val[1];
      }
    };

    const handlAmount = (val) => {
      data.openForm.contractAmount = Number(val);
    };

    // 获取负责人
    const handlHead = () => {
      // api.terminal.HEAD_PEOPLE(1).then((res) => {
      //   if (res.code === 0) {
      //     data.headList = res.data;
      //   }
      // });
      data.headList = crmStore.getters["company/getHeadOptions"] || []
    };

    // 负责人事件
    const handlChangeHead = (val) => {
      const index = data.headList.findIndex((a) => a.id === val);
      if (index !== -1) {
        data.openForm.contractHeadName = data.headList[index].realName;
      }
    };

    const handlDepartment = async () => {
      var a = await crmStore.dispatch("company/getDepartment");
      data.departmentList = a;
      // api.terminal.DEPARTMENT_LIST().then((res) => {
      //   if (res.code === 0) {
      //     data.departmentList = res.data;
      //   }
      // });
    };

    const handlCascader = (val) => {
      if (val) {
        data.openForm.value = val;
        const a = handlRecursive(data.departmentList, val[val.length - 1]);
        data.openForm.contractDepartmentId = a[a.length - 1].id;
        data.openForm.contractDepartmentName = a[a.length - 1].name;
      }
    };

    const handlRecursive = (arr, id) => {
      let oldList = [];
      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i].id) {
          oldList.push({ id: arr[i].id, name: arr[i].deptName });
          return oldList;
        } else if (arr[i].children && arr[i].children.length > 0) {
          const newList = handlRecursive(arr[i].children, id);
          if (newList && newList.length > 0) {
            oldList.push({ id: arr[i].id, name: arr[i].deptName });
            oldList = oldList.concat(newList);
            return oldList;
          }
        }
      }
    };

    const handlFile = () => {
      data.openForm.contractFile.forEach((item) => {
        // item.url = item.Value
        // item.name = item.Key
        item.code = "";
        item.isLong = 1;
        item.isNeed = 1;
        item.type = 1;
        item.validTime = "";
      });
    };

    const handlSubmit = () => {
      handlFile();
      data.openRef.validate((valid) => {
        if (valid) {
          const commit = ref(undefined);
          const msgs = ref("");
          if (data.openForm.id) {
            commit.value = api.terminal.SALES_UPDATE;
            msgs.value = "修改成功";
          } else {
            commit.value = api.terminal.SALES_CREATE;
            msgs.value = "创建成功";
          }
          commit.value(data.openForm).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: msgs.value,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    onMounted((_) => {
      handlHead();
      handlDepartment();
    });

    return {
      ...toRefs(data),
      close,
      remove,
      open,
      handlSubmit,
      handlDate,
      handlAmount,
      handlFile,
      handlHead,
      handlChangeHead,
      handlDepartment,
      handlCascader,
      handlRecursive,
      querySearchAsync,
      handleSelect,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
.col_title {
  height: 36px;
  width: 100%;
  line-height: 36px;
  background: rgb(248, 248, 248);
  padding-left: 10px;
  box-sizing: border-box;
}

:deep(.el-input__inner) {
  background-color: #fff;
}
</style>
